今天用useState()實作TodoList練習
App.js
import React,{useState} from "react";
import Form from "./components/Form";
import TodoList from "./components/TodoList";
const App = () => {
const [input,setInput] = useState("");
const [todos,setTodos] = useState([]);
return (
<div className="container">
<div className="app-box">
<div>
<h1 className='header'>TodoList</h1>
</div>
<div>
<Form
input={input}
setInput={setInput}
todos={todos}
setTodos={setTodos}
/>
</div>
<div>
<TodoList
todos = {todos}
setTodos = {setTodos}
/>
</div>
</div>
</div>
);
}
export default App;
Form.js
import React from 'react';
import {v4 as uuidv4} from "uuid";
const Form = ({input,setInput,todos,setTodos}) => {
const onInputChange = (event) =>{
setInput(event.target.value);
};
const onFormSubmit =(event)=>{
event.preventDefault(); //停止執行事件的默認動作
setTodos([...todos,{id:uuidv4(),title:input,completed:false}]);
setInput("");
};
return (
<form onSubmit = {onFormSubmit}>
<input
type="text"
className='line-input'
placeholder='Enter a Todo...'
value={input}
require
onChange={onInputChange}
/>
<button className='button-add' type='submit'>
Add
</button>
</form>
)
}
export default Form
TodoList.js
import React from 'react'
const TodoList = ({todos,setTodos}) => {
return (
<div>
{todos.map((todo)=>(
<li className='list-item' key={todo.id}>
<input type="text"
className='list'
value={todo.title}
onChange={(event)=>event.preventDefault()}
/>
</li>
))}
</div>
)
}
export default TodoList